package com.egdigital.allzic.push;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;

import com.egdigital.allzic.R;
import com.egdigital.allzic.utils.PrefManager;
import com.google.android.gms.gcm.GoogleCloudMessaging;

/**
 * legacy push manager
 */
public class PushManager {

	private static final String			TAG								= PushManager.class.getSimpleName();																	// log
	public static final String			PUSH_URL_GET_FORMAT_ENABLED		= "http://push.egdigital.fr/push/register_gcm/%s/%s/%s/%s/%s/%s/NULL/%s/enabled/enabled/enabled/%s";
	public static final String			PUSH_URL_GET_FORMAT_DISABLED	= "http://push.egdigital.fr/push/register_gcm/%s/%s/%s/%s/%s/%s/NULL/%s/disabled/disabled/disabled/%s";
	public static final String			PREF_REGISTRATION_ID			= "registration_id";
	public static final String			PREF_SENDER_ID					= "sender_id";
	private static final String			PREF_APP_VERSION				= "app_version";
	private static final String			PREF_ANDROID_ID					= "android_id";
	//
	private static GoogleCloudMessaging	mCloud;
	private static PushManager			mInstance;
	private static Context				mContext						= null;
	private static PrefManager			mPrefManager;
	//
	private static String				mRegistrationId					= "";

	private PushManager(Context context) {
		mContext = context;
		mPrefManager = PrefManager.getInstance(mContext);
		mPrefManager.addString_Pref(PREF_SENDER_ID, mContext.getString(R.string.sender_id));
		mPrefManager.addString_Pref(PREF_ANDROID_ID, getAndroidID(mContext));
		mPrefManager.addString_Pref(PREF_APP_VERSION, "" + getAppVersion(mContext));
	}

	public static PushManager getInstance(Context context) {
		if (mInstance == null) {
			synchronized (PushManager.class) {
				if (mInstance == null) {
					mInstance = new PushManager(context);
				}
			}
		}
		return mInstance;
	}

	/**
	 * Get the user google acount
	 */
	public static String getGoogleAccounts(Context context) {
		final StringBuilder builder = new StringBuilder();
		boolean builderEmpty = true;
		Account[] accounts = AccountManager.get(context).getAccountsByType("com.google");
		for (Account account : accounts) {
			if (builderEmpty) {
				builderEmpty = false;
			} else {
				builder.append(";");
			}
			builder.append(account.name);
		}
		return builder.toString();
	}

	/**
	 * Register to google server to get registration id
	 */
	public static void registerGCM() {
		mCloud = GoogleCloudMessaging.getInstance(mContext);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		mRegistrationId = mPrefManager.getString_prefForKey(PushManager.PREF_REGISTRATION_ID);
		if (mRegistrationId.isEmpty() && prefs.getBoolean("push", true)) {
			registerInBackground();
		} else {
			new AsyncTask<Void, Void, String>() {

				@Override
				protected String doInBackground(Void... params) {
					try {
						Looper.getMainLooper();
						sendRegistrationIdToBackend();
					} catch (Exception e) {
					}
					return null;
				}
			}.execute();
		}
	}

	private static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			// should never happen
			throw new RuntimeException("Could not get package name: " + e);
		}
	}

	private static String getAndroidID(final Context context) {
		String androidID = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
		if (androidID == null || androidID.equals("9774d56d682e549c")) {
			TelephonyManager tel = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			if (tel != null) {
				androidID = tel.getDeviceId();
				if (androidID == null || androidID.equals("")) {
					return null;
				}
				return "IMEI_" + androidID;
			} else {
				return null;
			}
		}
		return androidID;
	}

	private static void registerInBackground() {
		new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				try {
					Looper.getMainLooper();
					if (mCloud == null) {
						mCloud = GoogleCloudMessaging.getInstance(mContext);
					}
					// send registration to google server to get the registration id
					mRegistrationId = mCloud.register(mPrefManager.getString_prefForKey(PREF_SENDER_ID));
					// store the registration id
					mPrefManager.addString_Pref(PREF_REGISTRATION_ID, mRegistrationId);
					// send registration to egdigital server
					sendRegistrationIdToBackend();
				} catch (IOException ex) {
				}
				return "";
			}

			protected void onPostExecute(String result) {
			};
		}.execute();
	}

	private static void sendRegistrationIdToBackend() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		String urlPushFormatted;
		//
		if (prefs.getBoolean("push", true)) {
			urlPushFormatted = PUSH_URL_GET_FORMAT_ENABLED;
		} else
			urlPushFormatted = PUSH_URL_GET_FORMAT_DISABLED;
		String pushUrl = "";
		try {
			pushUrl = String.format(urlPushFormatted, mContext.getPackageName(), mPrefManager.getString_prefForKey(PREF_APP_VERSION), // Application
																																		// version
									mPrefManager.getString_prefForKey(PREF_ANDROID_ID), // id Android
									mPrefManager.getString_prefForKey(PREF_REGISTRATION_ID), // reg id
									URLEncoder.encode(Build.MANUFACTURER + "_" + Build.MODEL, "UTF-8"), // phone model
									String.valueOf(Build.VERSION.SDK_INT), // sdk
									URLEncoder.encode(getGoogleAccounts(mContext), "UTF-8"), Locale.getDefault().getLanguage()); // lang code
		} catch (UnsupportedEncodingException e) {
		}
		// post push
		AndroidHttpClient httpClient = AndroidHttpClient.newInstance("Android radio"); // radio name ?
		HttpGet httpGet = new HttpGet(pushUrl);
		HttpResponse answer = null;
		String result = "";
		//
		try {
			answer = httpClient.execute(httpGet);
			HttpEntity entity = answer.getEntity();
			result = EntityUtils.toString(entity);
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}
		httpClient.close();
	}
}
